import 'package:erp_widget/erp_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// The [DxChipsFormItem] widget is a text field that allows the user to input and create chips out of it.
/// github地址：https://github.com/danger-ahead/simple_chips_input
class DxChipsFormItem extends StatefulWidget {
  const DxChipsFormItem({
    super.key,
    this.constraints,
    this.margin = EdgeInsets.zero,
    this.padding = const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
    this.displayInput = true,
    this.dataList,
    this.placeChipsAbove = true,
    this.decoration = const BoxDecoration(color: Colors.white),
    this.formStyle = const DxChipFormStyle(),
    this.controller,
    this.deleteChip = true,
    this.deleteIcon = Icons.close,
    this.deleteIconColor = DxStyle.$CCCCCC,
    this.deleteIconSize = 14.0,
    this.checkFunction,
    this.onEditingComplete,
    this.onSubmit,
    this.onChipDelete,
  });

  final BoxConstraints? constraints;
  final EdgeInsets margin;

  /// Padding inside the main widget container;
  final EdgeInsets padding;

  /// 是否显示输入框
  final bool displayInput;

  /// 初始
  final List<String>? dataList;

  /// Decoration for the main widget container.
  final BoxDecoration decoration;

  /// Whether to place the chips section above or below the text field.
  final bool placeChipsAbove;

  /// Controller for the textfield.
  final TextEditingController? controller;

  /// Whether the chip should contain a delete method.
  final bool deleteChip;

  /// Icon for the delete method.
  final IconData deleteIcon;

  /// Delete icon size.
  final double deleteIconSize;

  /// Delete icon color.
  final Color deleteIconColor;

  /// Style for the textfield.
  final DxChipFormStyle formStyle;

  final bool Function(String v)? checkFunction;
  final void Function()? onEditingComplete;
  final void Function(String v)? onSubmit;

  /// Callback when a chip is deleted. Returns the deleted chip content and index.
  final void Function(String, int)? onChipDelete;

  @override
  State<DxChipsFormItem> createState() => _DxChipsFormItemState();
}

class _DxChipsFormItemState extends State<DxChipsFormItem> {
  late final TextEditingController _controller;
  late List<String> _chipsText;
  late final FocusNode _focusNode;
  late InputDecoration? _decoration;

  @override
  void initState() {
    super.initState();
    _controller = widget.controller ?? TextEditingController();
    _focusNode = FocusNode();

    InputDecoration? $decoration = widget.formStyle.decoration;
    _decoration = InputDecoration(
      icon: $decoration?.icon,
      iconColor: $decoration?.iconColor,
      label: $decoration?.label,
      labelText: $decoration?.labelText,
      labelStyle: $decoration?.labelStyle,
      hintText: $decoration?.hintText ?? '请输入',
      hintStyle: $decoration?.hintStyle ?? DxStyle.$CCCCCC$14,
      hintTextDirection: $decoration?.hintTextDirection,
      contentPadding: $decoration?.contentPadding ?? EdgeInsets.zero,
      prefixIcon: $decoration?.prefixIcon,
      prefixIconConstraints: $decoration?.prefixIconConstraints,
      prefix: $decoration?.prefix,
      prefixText: $decoration?.prefixText,
      prefixStyle: $decoration?.prefixStyle,
      prefixIconColor: $decoration?.prefixIconColor,
      suffixIcon: $decoration?.suffixIcon,
      suffix: $decoration?.suffix,
      suffixText: $decoration?.suffixText,
      suffixStyle: $decoration?.suffixStyle,
      suffixIconColor: $decoration?.suffixIconColor,
      suffixIconConstraints: $decoration?.suffixIconConstraints,
      border: $decoration?.border ?? InputBorder.none,
      enabled: $decoration?.enabled ?? true,
      constraints: $decoration?.constraints,
    );
  }

  List<Widget> _buildChipsSection() {
    final List<Widget> chipWidgetList = [];
    for (int i = 0; i < _chipsText.length; i++) {
      chipWidgetList.add(
        Chip(
          backgroundColor: DxStyle.$F8F8F8,
          labelPadding: const EdgeInsets.only(left: 5),
          visualDensity: const VisualDensity(vertical: -2),
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          label: Transform.translate(
            offset: const Offset(0, -1),
            child: Text(_chipsText[i], style: DxStyle.$CCCCCC$12),
          ),
          deleteIcon: Icon(widget.deleteIcon, size: widget.deleteIconSize, color: widget.deleteIconColor),
          onDeleted: () {
            widget.onChipDelete?.call(_chipsText[i], i);
            setState(() => _chipsText.removeAt(i));
          },
        ),
      );
    }
    return chipWidgetList;
  }

  @override
  Widget build(BuildContext context) {
    _chipsText = widget.dataList ?? [];
    return Container(
      constraints: widget.constraints ?? const BoxConstraints(minHeight: 56, minWidth: double.infinity),
      margin: widget.margin,
      padding: widget.padding,
      decoration: widget.decoration,
      child: Wrap(
        spacing: 8,
        runSpacing: 5,
        runAlignment: WrapAlignment.center,
        crossAxisAlignment: WrapCrossAlignment.center,
        children: [
          if (widget.placeChipsAbove) ..._buildChipsSection(),
          DxCondition.bool(
            widget.displayInput,
            trueBuilder: () => TextFormField(
              autofocus: widget.formStyle.autoFocus,
              focusNode: _focusNode,
              controller: _controller,
              style: DxStyle.$404040$15,
              keyboardType: widget.formStyle.keyboardType,
              maxLines: widget.formStyle.maxLines,
              minLines: widget.formStyle.minLines,
              enableSuggestions: widget.formStyle.enableSuggestions,
              showCursor: widget.formStyle.showCursor,
              cursorWidth: widget.formStyle.cursorWidth,
              cursorColor: widget.formStyle.cursorColor,
              cursorRadius: widget.formStyle.cursorRadius,
              cursorHeight: widget.formStyle.cursorHeight,
              decoration: _decoration,
              inputFormatters: widget.formStyle.inputFormatters,
              onEditingComplete: () => widget.onEditingComplete?.call(),
              onFieldSubmitted: ((value) {
                if (value.isNotEmpty) {
                  if (widget.checkFunction != null && widget.checkFunction!.call(value)) {
                    setState(() {
                      _chipsText.add(_controller.text);
                      _controller.clear();
                    });
                    widget.onSubmit?.call(value);
                  }
                } else {
                  /// 收起键盘
                  FocusScopeNode currentFocus = FocusScope.of(context);
                  if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
                    FocusManager.instance.primaryFocus?.unfocus();
                  }
                }
              }),
            ),
          ),
          if (!widget.placeChipsAbove) ..._buildChipsSection(),
        ],
      ),
    );
  }
}

/// Modifies the properties of the text field
class DxChipFormStyle {
  const DxChipFormStyle({
    this.autoFocus = false,
    this.maxLines = 1,
    this.minLines = 1,
    this.enableSuggestions = true,
    this.showCursor = true,
    this.cursorWidth = 2.0,
    this.cursorHeight,
    this.cursorRadius,
    this.cursorColor,
    this.keyboardType = TextInputType.text,
    this.inputFormatters,
    this.decoration,
  });

  final bool autoFocus;

  /// The maximum number of lines for the text field.
  final int maxLines;

  /// The minimum number of lines for the text field.
  final int minLines;

  /// whether to show suggestions
  final bool enableSuggestions;

  /// whether to show the cursor
  final bool showCursor;

  /// The width of the cursor.
  final double cursorWidth;

  /// The height of the cursor.
  final double? cursorHeight;

  /// The radius of the cursor.
  final Radius? cursorRadius;

  /// The color to use when painting the cursor.
  final Color? cursorColor;

  /// keyboard type for the textfield
  final TextInputType keyboardType;

  /// 验证规则
  final List<TextInputFormatter>? inputFormatters;

  /// The style of the textfield.
  final InputDecoration? decoration;
}
